<?php

namespace app\index\controller;

use app\services\ExcelService;
use think\Controller;
use think\Db;
use think\facade\Env;
use think\Request;

class File extends Controller
{
    //文件上传表单
    public function index()
    {
        return $this->fetch();
    }
    //文件上传提交
    public function upload(Request $request)
    {
//        ExcelService::import("/Users/lstink/Code/tp5/public/uploads/20200519/3ce471d7e91efe56991e6c5ae632ac57.xls");
        //获取表单上传文件
        $file = $request->file('files');
        if (empty($file)) {
            $this->error('请选择文件');
        }
        //移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['ext'=>'xlsx,xls'])->move('uploads');
        if ($info) {
            //导入
            $fileName = Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $info->getSaveName();
            $res = ExcelService::import($fileName);
            if ($res) {
                $this->success('内容解析成功',url('Index/index'));
            }else{
                $this->error('内容解析失败');
            }

        } else {
            //上传失败获取错误信息
            $this->error($file->getError());
        }
    }
}
